using ImoviesBlazor.Server.Data;

namespace ImoviesBlazor.Server.Repository.PlayLink
{
    public class PlaylinkRepository : IPlaylinkRepository
    {

        private readonly ApplicationDbContext _dbContext;

        public PlaylinkRepository(ApplicationDbContext dbContext)
        {
            this._dbContext = dbContext;
        }


        /// <summary>
        /// 从数据库中查询真实视频播放地址
        /// </summary>
        /// <param name="vcate">视频类型 Animation、Movie、Teleplay</param>
        /// <param name="url">视频url</param>
        /// <returns></returns>
        public string GetRealUrl(string vcate, string url)
        {
            switch (vcate)
            {
                case "Animation":
                    return _dbContext.AnimationVlinks.Where(x => x.Url == url).FirstOrDefault()?.RealUrl;
                case "Movie":
                    return _dbContext.MovieVlinks.Where(x => x.Url == url).FirstOrDefault()?.RealUrl;
                case "Teleplay":
                    return _dbContext.TeleplayVlinks.Where(x => x.Url == url).FirstOrDefault()?.RealUrl;
                default:
                    return null;
            }
        }


        /// <summary>
        /// 更新视频播放信息
        /// </summary>
        /// <param name="vcate">视频类型</param>
        /// <param name="url">播放地址</param>
        /// <param name="realUrl">真实地址</param>
        /// <returns></returns>
        public bool UpdateLinkInfo(string vcate, string url, string realUrl)
        {
            switch (vcate)
            {
                case "Animation":
                    var apl = _dbContext.AnimationVlinks.Where(x => x.Url == url).FirstOrDefault();
                    if (apl == null)
                    {
                        return false;
                    }
                    _dbContext.Attach(apl);
                    apl.RealUrl = realUrl;
                    return _dbContext.SaveChanges() > 0;
                case "Movie":
                    var mpl = _dbContext.MovieVlinks.Where(x => x.Url == url).FirstOrDefault();
                    if (mpl == null)
                    {
                        return false;
                    }
                    _dbContext.Attach(mpl);
                    mpl.RealUrl = realUrl;
                    return _dbContext.SaveChanges() > 0;
                case "Teleplay":
                    var tpl = _dbContext.TeleplayVlinks.Where(x => x.Url == url).FirstOrDefault();
                    if (tpl == null)
                    {
                        return false;
                    }
                    _dbContext.Attach(tpl);
                    tpl.RealUrl = realUrl;
                    return _dbContext.SaveChanges() > 0;
                default:
                    return false;
            }
        }
    }
}